package com.ssy.lingxi.platform.template.service.serviceimpl.web;

import cn.hutool.core.collection.CollectionUtil;
import com.ssy.lingxi.common.constant.tree.Node;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.template.api.model.dto.inner.CategorySortDTO;
import com.ssy.lingxi.platform.template.service.entity.adorn.PageTemplateBrand;
import com.ssy.lingxi.platform.template.service.entity.adorn.PageTemplateFirstCategory;
import com.ssy.lingxi.platform.template.service.model.dto.common.TemplateIdDTO;
import com.ssy.lingxi.platform.template.service.model.vo.adorn.BrandVO;
import com.ssy.lingxi.platform.template.service.model.vo.adorn.CategoryVO;
import com.ssy.lingxi.platform.template.service.model.vo.web.CategoryTreeVO;
import com.ssy.lingxi.platform.template.service.repository.PageTemplateBrandRepository;
import com.ssy.lingxi.platform.template.service.repository.PageTemplateFirstCategoryRepository;
import com.ssy.lingxi.platform.template.service.service.web.CategoryWebService;
import com.ssy.lingxi.search.api.feign.ITemplateFeign;
import com.ssy.lingxi.search.api.model.response.BrandResponse;
import com.ssy.lingxi.search.api.model.response.CategoryResponse;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fhj
 * @version 2.0.0
 * web - 平台品类 - 业务实现层
 * @date 2020/12/15
 */
@Slf4j
@Service
public class CategoryWebServiceImpl implements CategoryWebService {

    @Resource
    private PageTemplateBrandRepository pageTemplateBrandRepository;
    @Resource
    private ITemplateFeign templateFeign;
    @Resource
    private PageTemplateFirstCategoryRepository pageTemplateFirstCategoryRepository;

    @Override
    @ApiOperation(value = "获取平台首页平台品类树")
    public Wrapper<List<Node>> findPlatformCategoryTree(Long shopId) {
        //调用搜索服务 -> 获取全部商品品类树（平台品类）
        Wrapper<List<Node>> categoryWrapper = templateFeign.getCategoryTree(shopId, null, null);
        if (categoryWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", categoryWrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        if (CollectionUtil.isEmpty(categoryWrapper.getData())) {
            log.info("获取不到平台品类树（检查平台后台是否添加了品类）");
            return Wrapper.success(new ArrayList<>());
        }

        return Wrapper.success(categoryWrapper.getData());
    }

    @Override
    @ApiOperation(value = "获取企业商城首页平台品类树")
    public Wrapper<List<CategoryTreeVO>> findEnterpriseCategoryTree(TemplateIdDTO dto, Long shopId) {
        //调用搜索服务 -> 获取全部商品品类树（平台品类）
        Wrapper<List<Node>> categoryWrapper = templateFeign.getCategoryTree(shopId, null, null);
        if (categoryWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", categoryWrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        if (CollectionUtil.isEmpty(categoryWrapper.getData())) {
            log.info("获取不到平台品类树（检查平台后台是否添加了品类）");
            return Wrapper.success(new ArrayList<>());
        }

        //根据平台一级品类获取到关联的推荐品牌并封装到品类树进去
        List<CategoryTreeVO> categoryTreeVOList = categoryWrapper.getData().stream().map(n -> {
            CategoryTreeVO vo = new CategoryTreeVO();
            vo.setId(Long.parseLong(n.getId()));
            vo.setTitle(n.getTitle());
            vo.setParentId(n.getParentId());
            vo.setChecked(n.getChecked());
            vo.setChildren(n.getChildren());
            PageTemplateBrand pageTemplateBrand = pageTemplateBrandRepository.findByTemplateIdAndCategoryId(dto.getTemplateId(), Long.parseLong(n.getId()));
            if (pageTemplateBrand != null && CollectionUtil.isNotEmpty(pageTemplateBrand.getBrandIds())) {
                Wrapper<PageData<BrandResponse>> brandWrapper = templateFeign.getBrandList(1, 10, null, null, Long.parseLong(n.getId()), null, null, null, null, pageTemplateBrand.getBrandIds(), null);
                if (brandWrapper.getData() != null && CollectionUtil.isNotEmpty(brandWrapper.getData().getData())) {
                    List<BrandVO> brandList = brandWrapper.getData().getData().stream().map(brand -> {
                        BrandVO brandVO = new BrandVO();
                        brandVO.setBrandId(brand.getId());
                        brandVO.setBrandLogo(brand.getLogoUrl());
                        brandVO.setBrandName(brand.getName());
                        return brandVO;
                    }).collect(Collectors.toList());
                    vo.setBrandList(brandList);
                }
            }
            return vo;
        }).collect(Collectors.toList());

        return Wrapper.success(categoryTreeVOList);
    }

    @Override
    @ApiOperation(value = "获取企业直采平台品类树")
    public Wrapper<List<Node>> findPurchaseCategoryTree() {
        //调用搜索服务 -> 获取全部商品品类树（平台品类）
        Wrapper<List<Node>> categoryWrapper = templateFeign.getCategoryTree(null, null, null);
        if (categoryWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", categoryWrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        if (CollectionUtil.isEmpty(categoryWrapper.getData())) {
            log.info("获取不到平台品类树（检查平台后台是否添加了品类）");
            return Wrapper.success(new ArrayList<>());
        }

        return Wrapper.success(categoryWrapper.getData());
    }

    @Override
    @ApiOperation(value = "获取所有一级平台品类")
    public Wrapper<List<CategoryVO>> findAllFirstCategory(Long shopId, Long templateId) {
        if (templateId == null) {
            return Wrapper.fail("模板ID不能为空");
        }
        List<PageTemplateFirstCategory> pageTemplateFirstCategories = pageTemplateFirstCategoryRepository.findAllByShopIdAndTemplateId(shopId, templateId);
        //调用搜索服务 -> 获取所有一级平台品类
        Wrapper<List<CategoryResponse>> wrapper = templateFeign.getFirstCategoryListByMemberId(shopId, null, null);
        if (CollectionUtil.isEmpty(pageTemplateFirstCategories)) {
            if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
                log.info("请求搜索服务失败:{}", wrapper.getMessage());
                return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
            }
            if (CollectionUtil.isEmpty(wrapper.getData())) {
                log.info("获取不到一级平台品类（检查平台后台是否添加了品类）");
                return Wrapper.success(new ArrayList<>());
            }
            //保存一份数据到本地数据库
            pageTemplateFirstCategories = wrapper.getData().stream().map(c -> {
                PageTemplateFirstCategory vo = new PageTemplateFirstCategory();
                vo.setTemplateId(templateId);
                vo.setCategoryId(c.getId());
                vo.setCategoryName(c.getName());
                vo.setShopId(shopId);
                vo.setMemberId(null);
                vo.setRoleId(null);
                vo.setSort(c.getSort());
                return vo;
            }).collect(Collectors.toList());
            //批量保存
            pageTemplateFirstCategoryRepository.saveAll(pageTemplateFirstCategories);
            //拼装返回
            return Wrapper.success(wrapper.getData().stream().map(c -> {
                CategoryVO vo = new CategoryVO();
                vo.setCategoryId(c.getId());
                vo.setCategoryName(c.getName());
                vo.setId(c.getId());
                vo.setName(c.getName());
                return vo;
            }).collect(Collectors.toList()));
        } else {
            //先保存商品服务新增的数据
            List<Long> categoriesIds = pageTemplateFirstCategories.stream().map(PageTemplateFirstCategory::getCategoryId).collect(Collectors.toList());//本地数据库商品id
            if (!CollectionUtils.isEmpty(categoriesIds)) {
                List<CategoryResponse> data = wrapper.getData();
                if (!CollectionUtils.isEmpty(data)) {
                    List<PageTemplateFirstCategory> pageTemplateFirstCategoryList = data.stream().filter(p -> !categoriesIds.contains(p.getId())).map(c -> {
                        PageTemplateFirstCategory vo = new PageTemplateFirstCategory();
                        vo.setTemplateId(templateId);
                        vo.setCategoryId(c.getId());
                        vo.setCategoryName(c.getName());
                        vo.setShopId(shopId);
                        vo.setMemberId(null);
                        vo.setRoleId(null);
                        vo.setSort(c.getSort());
                        return vo;
                    }).collect(Collectors.toList());
                    //批量保存
                    pageTemplateFirstCategoryRepository.saveAll(pageTemplateFirstCategoryList);
                }

            }
            pageTemplateFirstCategories = pageTemplateFirstCategoryRepository.findAllByShopIdAndTemplateId(shopId, templateId);
            List<CategoryVO> categoryVOS = pageTemplateFirstCategories.stream().map(c -> {
                CategoryVO vo = new CategoryVO();
                vo.setCategoryId(c.getCategoryId());
                vo.setCategoryName(c.getCategoryName());
                vo.setId(c.getCategoryId());
                vo.setName(c.getCategoryName());
                vo.setIsShow(c.getIsShow());
                vo.setSort(c.getSort());
                return vo;
            }).collect(Collectors.toList());

            return Wrapper.success(categoryVOS.stream().filter(e->e.getId()!=null&&e.getSort()!=null).sorted(Comparator.comparingLong(CategoryVO::getSort)).collect(Collectors.toList()));
        }

    }

    /**
     * 更新品类排序序号
     *
     * @param dto 请求实体
     * @return 操作结果
     */
    @Override
    public Void updateCategorySort(CategorySortDTO dto) {
        List<PageTemplateFirstCategory> pageTemplateFirstCategories = pageTemplateFirstCategoryRepository.findAllByCategoryId(dto.getCategoryId());
        if (pageTemplateFirstCategories.size() > 0) {
            pageTemplateFirstCategories.forEach(p -> p.setSort(dto.getSort()));
            pageTemplateFirstCategoryRepository.saveAll(pageTemplateFirstCategories);
            pageTemplateFirstCategoryRepository.flush();
        }
        return null;
    }
    /*    @Override
    @ApiOperation(value = "获取所有一级平台品类")
    public Wrapper<List<CategoryVO>> findAllFirstCategory(Long shopId) {
        //调用搜索服务 -> 获取所有一级平台品类
        Wrapper<List<CategoryResponse>> wrapper = templateFeign.getFirstCategoryListByMemberId(shopId, null, null);
        if(wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        if(CollectionUtil.isEmpty(wrapper.getData())) {
            log.info("获取不到一级平台品类（检查平台后台是否添加了品类）");
            return Wrapper.success(new ArrayList<>());
        }

        //拼装返回
        return Wrapper.success(wrapper.getData().stream().map(c -> {
            CategoryVO vo = new CategoryVO();
            vo.setCategoryId(c.getId());
            vo.setCategoryName(c.getName());
            vo.setId(c.getId());
            vo.setName(c.getName());
            return vo;
        }).collect(Collectors.toList()));
    }*/
}
